import Cookies from 'js-cookie';
import { getRoutes } from '@/api/routes';
import Layout from '@/layout';

export default {
  namespaced: true,
  state: {
    sidebar: {
      opened: Cookies.get('sidebarStatus') ? !!+Cookies.get('sidebarStatus') : true,
      withoutAnimation: false
    },
    device: 'desktop',
    routes: []
  },
  mutations: {
    TOGGLE_SIDEBAR: state => {
      state.sidebar.opened = !state.sidebar.opened;
      state.sidebar.withoutAnimation = false;
      if (state.sidebar.opened) {
        Cookies.set('sidebarStatus', 1);
      } else {
        Cookies.set('sidebarStatus', 0);
      }
    },
    CLOSE_SIDEBAR: (state, withoutAnimation) => {
      Cookies.set('sidebarStatus', 0);
      state.sidebar.opened = false;
      state.sidebar.withoutAnimation = withoutAnimation;
    },
    TOGGLE_DEVICE: (state, device) => {
      state.device = device;
    },
    // 路由
    SET_ROUTES: (state, routes) => {
      state.routes = routes;
    }
  },
  actions: {
    toggleSideBar({ commit }) {
      commit('TOGGLE_SIDEBAR');
    },
    closeSideBar({ commit }, { withoutAnimation }) {
      commit('CLOSE_SIDEBAR', withoutAnimation);
    },
    toggleDevice({ commit }, device) {
      commit('TOGGLE_DEVICE', device);
    },
    getRoutes({ commit }) {
      return new Promise((resolve, reject) => {
        getRoutes().then((res) => {
          // eslint-disable-next-line eqeqeq
          if (res.code == 0) {
            const routes = routeHandle(res.data);
            commit('SET_ROUTES', routes);
            resolve(routes);
          } else {
            reject();
          }
        }).catch(error => {
          console.log(error);
          reject(error);
        });
      });
    }
  }
};

function routeHandle(routes) {
  const routers = [];
  routes.forEach((item) => {
    const route = Object.assign({}, item);
    if (route.children && route.children.length) {
      route.component = Layout;
      route.children = routeHandle(route.children);
    } else {
      if (!(/^http/.test(route.redirect || route.path))) {
        route.component = () => require.ensure([], (require) => require(`@/views${route.redirect || route.path}/index`));
      }
    }
    routers.push(route);
  });
  return routers;
}
